/*
题目地址:https://leetcode-cn.com/problems/license-key-formatting/
题目标签:字符串
*/

#include <string>
using namespace std;

class Solution {
   public:
    string licenseKeyFormatting(string s, int k) {
        // 添加破折号
        string ans = "";
        int now = k;  //当前分组剩余字符数
        for (int i = s.size() - 1; i >= 0; i--) {
            if (s[i] != '-') {
                if (now == 0) {  // 保证前面还有字母，避免在前面添加多余的破折号
                    if (ans.size() != 0) {  //避免在后面添加多余的破折号
                        ans.push_back('-');
                    }
                    now = k;
                }
                ans.push_back(toupper(s[i]));
                now -= 1;
            }
        }
        reverse(ans.begin(), ans.end());
        return ans;
    }
};